<!DOCTYPE html>
<html lang="zh-CN">
<head hexo-theme='https://github.com/volantis-x/hexo-theme-volantis/tree/4.1.5'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta http-equiv='x-dns-prefetch-control' content='on' />
  <link rel='dns-prefetch' href='https://cdn.jsdelivr.net'>
  <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <!-- 页面元数据 -->
  
  <title>webpack4.0进阶（三） - Alan|前端博客</title>
  
    <meta name="keywords" content="webpack4.0">
  

  
    <meta name="description" content="手写简单的loader、Plugin、简单的webpack">
  

  <!-- feed -->
  

  <!-- import meta -->
  

  <!-- link -->
  
    <link rel="shortcut icon" type='image/x-icon' href="https://gitee.com/alannum3/MyImages/raw/master/img/basketball-ball.png">
  

  <!-- import link -->
  

  
    
<link rel="stylesheet" href="/css/first.css">

  

  
  <link rel="stylesheet" href="/css/style.css" media="print" onload="this.media='all';this.onload=null">
  <noscript><link rel="stylesheet" href="/css/style.css"></noscript>
  

  <script id="loadcss"></script>

</head>

<body>
  

<header id="l_header" class="l_header auto shadow blur " style='opacity: 0' >
  <div class='container'>
  <div id='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h m-phone' id="pjax-header-nav-list">
        <li><a id="s-comment" class="fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a id="s-toc" class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/'>
          
          
            <i class='fas fa-basketball-ball'></i>
          
          
            Alan
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h m-pc'>
          
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/
                  
                  
                  
                    id="categories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/archives/
                  
                  
                  
                    id="archives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/friends/
                  
                  
                  
                    id="friends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box header toggle-mode-btn">
                  <i class='fas fa-moon fa-fw'></i>dark
                </a>
              <li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  <i class='fas fa-ellipsis-v fa-fw'></i>更多
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://alanwang.avosapps.us/
                  
                  
                    target="_blank"
                  
                  
                    id="https:alanwangavosappsus"
                  >
                  <i class='fas fa-comments fa-fw'></i>评论管理
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="Search..." />
        </form>
      </div>

			<ul class='switcher nav-list-h m-phone'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/categories/
                  
                  
                  
                    id="categories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/archives/
                  
                  
                  
                    id="archives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/friends/
                  
                  
                  
                    id="friends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box header toggle-mode-btn">
                  <i class='fas fa-moon fa-fw'></i>dark
                </a>
              <li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  <i class='fas fa-ellipsis-v fa-fw'></i>更多
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://alanwang.avosapps.us/
                  
                  
                    target="_blank"
                  
                  
                    id="https:alanwangavosappsus"
                  >
                  <i class='fas fa-comments fa-fw'></i>评论管理
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

  <div id="l_body">
    <div id="l_cover">
  
    
        <div id="half" class='cover-wrapper post focus' style="display: ;">
          
            <div id='cover-backstretch'></div>
          
          <div class='cover-body'>
  <div class='top'>
    
    
      <p class="title">Alan</p>
    
    
      <p class="subtitle">此刻想举重若轻，之前必要负重前行</p>
    
  </div>
  <div class='bottom'>
    <div class='menu navigation'>
      <div class='list-h'>
        
          
            <a href="https://alannum3.gitee.io/"
              
              
              id="https:alannum3giteeio">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f389.svg'><p>Next.js博客</p>
            </a>
          
        
      </div>
    </div>
  </div>
</div>

          <div id="scroll-down" style="display: none;"><i class="fa fa-chevron-down scroll-down-effects"></i></div>
        </div>
    
  
  </div>

    <div id='safearea'>
      <div class='body-wrapper' id="pjax-container">
        

<div class='l_main'>
  <article class="article post white-box reveal md shadow article-type-post" id="post" itemscope itemprop="blogPost">
  


  
  <div class="article-meta" id="top">
    
    
    
      <h1 class="title">
        webpack4.0进阶（三）
      </h1>
      <div class='new-meta-box'>
        
          
            
  <div class='new-meta-item category'>
    <a class='notlink'>
      <i class="fas fa-folder-open fa-fw" aria-hidden="true"></i>
      <a class="category-link" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a><span class="sep"></span><a class="category-link" href="/categories/%E5%89%8D%E7%AB%AF/webpack4-0%E5%AD%A6%E4%B9%A0%E6%80%BB%E7%BB%93/">webpack4.0学习总结</a>
    </a>
  </div>


          
        
          
            <div class="new-meta-item date" itemprop="dateUpdated" datetime="2020-06-13T16:06:00+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2020年6月13日 16:06</p>
  </a>
</div>

          
        
          
            
  <div class="new-meta-item wordcount">
    <a class='notlink'>
      <i class="fas fa-keyboard fa-fw" aria-hidden="true"></i>
      <p>字数：2.1k字</p>
    </a>
  </div>
  <div class="new-meta-item readtime">
    <a class='notlink'>
      <i class="fas fa-hourglass-half fa-fw" aria-hidden="true"></i>
      <p>时长：10分钟</p>
    </a>
  </div>


          
        
          
            
  <div class="new-meta-item browse leancloud">
    <a class='notlink'>
      
      <div id="lc-pv" data-title="webpack4.0进阶（三）" data-path="/posts/f9d92613/">
        <i class="fas fa-fire fa-fw" aria-hidden="true"></i>
        <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
        次浏览
      </div>
    </a>
  </div>


          
        
      </div>
    
  </div>


  
  <p>手写简单的loader、Plugin、简单的webpack</p>
<a id="more"></a>

<h3 id="手写简单的loader"><a href="#手写简单的loader" class="headerlink" title="手写简单的loader"></a>手写简单的loader</h3><p>目录</p>
<pre><code>myLoader
 ├── loaders
 │   └── myLoader.js
 ├── package.json
 ├── src
 │   └── index.js
 └── webpack.config.js</code></pre><div class="tabs" id="1"><ul class="nav-tabs"><li class="tab active"><a class="#1-1">index.js</a></li><li class="tab"><a class="#1-2">webpack.config.js</a></li><li class="tab"><a class="#1-3">myLoader.js</a></li></ul><div class="tab-content"><div class="tab-pane active" id="1-1"><pre><code class="js"><span class="built_in">console</span>.log(<span class="string">'hello webpack!'</span>);</code></pre></div><div class="tab-pane" id="1-2"><pre><code class="js"><span class="keyword">const</span> path =<span class="built_in">require</span>(<span class="string">'path'</span>);

<span class="built_in">module</span>.exports = {
  mode: <span class="string">'development'</span>,
  entry: <span class="string">'./src/index.js'</span>,
  <span class="built_in">module</span>: {
    rules: [{
      test: <span class="regexp">/\.js$/</span>,
      exclude: <span class="regexp">/node_modules/</span>,
      use: [
        {
          loader: path.resolve(__dirname, <span class="string">'./loaders/myLoader.js'</span>),
          options: {
            key: <span class="string">'my option value'</span>,
          },
        },
      ],
    }],
  },
  output: {
    path: path.resolve(__dirname, <span class="string">'dist'</span>),
    filename: <span class="string">'[name].js'</span>,
  },
};</code></pre></div><div class="tab-pane" id="1-3"><pre><code class="js"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span> (<span class="params">source</span>) </span>{
  <span class="keyword">return</span> source.replace(<span class="string">'webpack'</span>, <span class="keyword">this</span>.query.key);
}</code></pre></div></div></div>

<p>这个例子非常简单，就是通过自建的loader将项目中的<strong>webpack</strong>字符串替换成webpack中配置的字符串。<code>myLoader.js</code>中可以通过<code>this.query</code>接受webpack中配置的options参数。更多this上的<a href="https://webpack.js.org/api/loaders/#the-loader-context" target="_blank" rel="noopener">属性参考</a>（包括异步处理、回调…）</p>
<p>上面的例子通过打包后代码如下</p>
<pre><code class="js">console.log(&#39;hello my option value!&#39;)</code></pre>
<p><strong>webpack5</strong>中可以直接通过<code>this.getOptions (schema)</code>来获取options参数</p>
<p><strong>webpack resolveLoader:</strong></p>
<p>和之前提到的resolve的使用类似，就是用来偷懒的😂</p>
<p>使用<code>resolveLoader</code>改写后的wepack.config.js</p>
<pre><code class="js">const path =require(&#39;path&#39;);

module.exports = {
  mode: &#39;development&#39;,
  entry: &#39;./src/index.js&#39;,
  resolveLoader: {
    modules: [&#39;node_modules&#39;, &#39;./loaders&#39;],
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: [
        {
          loader: &#39;myLoader&#39;,
          options: {
            key: &#39;my option&#39;,
          },
        },
      ],
    }],
  },
  output: {
    path: path.resolve(__dirname, &#39;dist&#39;),
    filename: &#39;[name].js&#39;,
  },
};</code></pre>
<p>上面这个例子可以直接使用<code>myLoader</code>名，webpack会在<code>node_modules</code> 和<code>./loaders</code>中寻找对应的Loader。</p>
<div class="note warning"><p>自定义的loader中不要使用箭头函数，会产生this指向问题</p></div>



<h3 id="手写简单的Plugin"><a href="#手写简单的Plugin" class="headerlink" title="手写简单的Plugin"></a>手写简单的Plugin</h3><p>目录</p>
<pre><code>myPlugin
 ├── package.json
 ├── plugins
 │   └── date-webpack-plugin.js
 ├── src
 │   └── index.js
 └── webpack.config.js</code></pre><p><a href="https://webpack.js.org/api/compiler-hooks/" target="_blank" rel="noopener">complier提供了许多钩子</a>，可以让我们在打包的不同时刻来进行不同的处理，这里使用了<code>emit</code>钩子</p>
<p>下面通过手写的plugin来实现在dist目录下生成一个<code>author.txt</code>文件</p>
<div class="tabs" id="2"><ul class="nav-tabs"><li class="tab active"><a class="#2-1">date-webpack-plugin.js</a></li><li class="tab"><a class="#2-2">webpack.config.js</a></li></ul><div class="tab-content"><div class="tab-pane active" id="2-1"><pre><code class="js"><span class="class"><span class="keyword">class</span> <span class="title">DateWebpackPlugin</span> </span>{
  <span class="keyword">constructor</span>(options) {
    <span class="comment">// options是new插件时传进来的参数</span>
    <span class="keyword">this</span>.options = options;
  }

  apply(compiler) {
    <span class="keyword">const</span> _this = <span class="keyword">this</span>;
    compiler.hooks.emit.tapAsync(<span class="string">'DateWebpackPlugin'</span>, (compilation, cb) =&gt; {
      compilation.assets[<span class="string">'author.txt'</span>] = {
        <span class="comment">// 返回的资源</span>
        source: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{
          <span class="keyword">return</span> <span class="string">`created by <span class="subst">${_this.options.author}</span> <span class="subst">${<span class="keyword">new</span> <span class="built_in">Date</span>()}</span>`</span>;
        },
        <span class="comment">// 最后生成的文件大小</span>
        size: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{
          <span class="keyword">return</span> <span class="number">19</span>;
        }
      };
      <span class="comment">// 由于emit是异步操作，所以最后要执行回调函数</span>
      cb();
    })
  }
}

<span class="built_in">module</span>.exports = DateWebpackPlugin;</code></pre></div><div class="tab-pane" id="2-2"><pre><code class="js"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);
<span class="keyword">const</span> DateWebpackPlugin = <span class="built_in">require</span>(<span class="string">'./plugins/date-webpack-plugin'</span>);

<span class="built_in">module</span>.exports = {
  mode: <span class="string">'development'</span>,
  entry: <span class="string">'./src/index.js'</span>,
  output: {
    path: path.resolve(__dirname, <span class="string">'dist'</span>),
    filename: <span class="string">'[name].js'</span>,
  },
  plugins: [
    <span class="keyword">new</span> DateWebpackPlugin({
      author: <span class="string">'Alan'</span>,
    }),
  ],
};</code></pre></div></div></div>

<p>打包后会在dist目录下自动生成一个author.txt文件，内容如下</p>
<pre><code>created by AlanSun Jun 07 2020 11:49:42 GMT+0800 (GMT+08:00)</code></pre><h3 id="react和vue脚手架webpack配置"><a href="#react和vue脚手架webpack配置" class="headerlink" title="react和vue脚手架webpack配置"></a>react和vue脚手架webpack配置</h3><ul>
<li>create-react-app通过<code>npm run eject</code>暴露webpack配置</li>
<li>vue-cli通过<a href="https://cli.vuejs.org/zh/config/#vue-config-js" target="_blank" rel="noopener">vue.config.js</a>配置webpack(可以通过configureWebpack自定义webpack配置)</li>
</ul>
<h3 id="手写一个简单的webpack打包工具"><a href="#手写一个简单的webpack打包工具" class="headerlink" title="手写一个简单的webpack打包工具"></a>手写一个简单的webpack打包工具</h3><p>先提前安装以下需要的插件</p>
<pre><code>npm i @babel/parser -D // 将js内容转化为抽象语法树
npm i @babel/traverse -D // 用来遍历抽象语法树
npm i @babel/core -D
npm i @babel/preset-env -D //es6-&gt;es5
npm i cli-highlight -D // 可选，命令行高亮插件</code></pre><p>前置知识：</p>
<p><strong>node：</strong></p>
<ul>
<li><a href="http://nodejs.cn/api/fs.html#fs_fs_readfilesync_path_options" target="_blank" rel="noopener">fs.readFileSync</a>(同步读取文件内容)</li>
<li><a href="http://nodejs.cn/api/path.html#path_path_dirname_path" target="_blank" rel="noopener">path_dirname</a>(获取文件的目录)</li>
</ul>
<p><strong>项目目录：</strong></p>
<pre><code>bundler
 ├── bundler.js  // 主要文件
 └── src
     ├── course.js
     ├── index.js
     └── learn.js</code></pre><div class="tabs" id="3"><ul class="nav-tabs"><li class="tab active"><a class="#3-1">index.js</a></li><li class="tab"><a class="#3-2">learn.js</a></li><li class="tab"><a class="#3-3">course.js</a></li></ul><div class="tab-content"><div class="tab-pane active" id="3-1"><pre><code class="js"><span class="keyword">import</span> notify <span class="keyword">from</span> <span class="string">'./learn.js'</span>;

<span class="built_in">console</span>.log(notify);</code></pre></div><div class="tab-pane" id="3-2"><pre><code class="js"><span class="keyword">import</span> { course } <span class="keyword">from</span> <span class="string">'./course.js'</span>;

<span class="keyword">const</span> learnNotify = <span class="string">`time to learn <span class="subst">${course}</span>`</span>;

<span class="keyword">export</span> <span class="keyword">default</span> learnNotify;</code></pre></div><div class="tab-pane" id="3-3"><pre><code class="js"><span class="keyword">export</span> <span class="keyword">const</span> course = <span class="string">'webpack'</span>;</code></pre></div></div></div>

<p>我将整个项目拆分成2个部分来分析</p>
<h4 id="处理入口文件找到所有import文件"><a href="#处理入口文件找到所有import文件" class="headerlink" title="处理入口文件找到所有import文件"></a>处理入口文件找到所有import文件</h4><p>思路：</p>
<ol>
<li>通过fs.readFileSync读取index.js的内容</li>
<li>使用@babel/parser将读取的内容转化为AST抽象语法树</li>
<li>使用@babel/traverse遍历找到所有import语句</li>
<li>分析出引用的文件，保存其路径</li>
</ol>
<p>代码：</p>
<pre><code class="js">const fs = require(&#39;fs&#39;);
const parser = require(&#39;@babel/parser&#39;);
const traverse = require(&#39;@babel/traverse&#39;).default;
// 命令行高亮工具
const highlight = require(&#39;cli-highlight&#39;).highlight

const moduleAnalysis = (filename) =&gt; {
  // 读取出index.js文件内容
  const content = fs.readFileSync(filename, &#39;utf-8&#39;);
  // 将文件内容转化为抽象语法树
  const ast = parser.parse(content, {
    sourceType: &#39;module&#39;
  });
  // 遍历抽象语法树
  traverse(ast, {
    ImportDeclaration({ node }) {
      console.log(node);
    }
  })
  // console.log(highlight(ast));
  console.log(ast.program.body);
}
moduleAnalysis(&#39;./src/index.js&#39;);</code></pre>
<p><img src="" data-original="https://gitee.com/alannum3/MyImages/raw/master/img/image-20200612111622662.png" alt="通过parser转化成的抽象语法树"></p>
<p>通过上图可以清楚看到我们现在要做的事情就是找到所有为type为<code>importDeclaration</code>的node属性</p>
<p><img src="" data-original="https://gitee.com/alannum3/MyImages/raw/master/img/image-20200612112106327.png" alt="使用traverse得到的ImportDeclaration"></p>
<p>最后对js文件进行babel处理，转化成浏览器能够识别的代码</p>
<p>完整代码</p>
<pre><code class="js">const fs = require(&#39;fs&#39;);
const parser = require(&#39;@babel/parser&#39;);
const traverse = require(&#39;@babel/traverse&#39;).default;
const path = require(&#39;path&#39;);
const babel = require(&#39;@babel/core&#39;);
// 命令行高亮工具
const highlight = require(&#39;cli-highlight&#39;).highlight

const moduleAnalysis = (filename) =&gt; {
  // 读取出index.js文件内容
  const content = fs.readFileSync(filename, &#39;utf-8&#39;);
  // 将文件内容转化为抽象语法树
  const ast = parser.parse(content, {
    sourceType: &#39;module&#39;
  });
  const dependencies = {};
  // 遍历抽象语法树
  traverse(ast, {
    ImportDeclaration({ node }) {
      // 文件对应目录./src
      const dirPath = path.dirname(filename);
      // 绝对路径./src/learn.js(window操作系统)
      let filePath = (&#39;./&#39; + path.join(dirPath, node.source.value)).replace(&#39;\\&#39;, &#39;/&#39;);
      dependencies[node.source.value] = filePath;
      // { &#39;./learn.js&#39;: &#39;./src/learn.js&#39; }
      console.log(dependencies);
    }
  });
  // 转化成浏览器可以执行的代码
  const { code } = babel.transformFromAst(ast, null, {
    presets: [&#39;@babel/preset-env&#39;]
  });
  console.log(highlight(code));
  return {
    filename,
    dependencies,
    code
  }
}
moduleAnalysis(&#39;./src/index.js&#39;);</code></pre>
<h4 id="通过入口文件分析出所有文件依赖"><a href="#通过入口文件分析出所有文件依赖" class="headerlink" title="通过入口文件分析出所有文件依赖"></a>通过入口文件分析出所有文件依赖</h4><p>上面已经分析出了入口文件的一些依赖，接下来可以通过递归遍历来分析出所有的文件依赖并保存在变量中，先分析一些经过上面函数处理后的数据</p>
<pre><code class="json">{
  filename: &#39;./src/index.js&#39;,
  dependencies: { &#39;./learn.js&#39;: &#39;./src/learn.js&#39; },
  code: &#39;&quot;use strict&quot;;\n&#39; +
    &#39;\n&#39; +
    &#39;var _learn = _interopRequireDefault(require(&quot;./learn.js&quot;));\n&#39; +
    &#39;\n&#39; +
    &#39;function _interopRequireDefault(obj) { return obj &amp;&amp; obj.__esModule ? obj : { &quot;default&quot;: obj }; }\n&#39; +
    &#39;\n&#39; +
    &#39;console.log(_learn[&quot;default&quot;]);&#39;
}</code></pre>
<p>我们只需要遍历对象中的dependencies属性，把里面的路径名传入到上面的<code>moduleAnalysis</code>函数中，最终获取所有的依赖信息。</p>
<p>具体代码如下</p>
<pre><code class="js">const analysisDependenciesGraph = (entry) =&gt; {
  const entryModule = moduleAnalysis(entry);
  const graphList = [entryModule];
  for (let i = 0; i &lt; graphList.length; i++) {
    const item = graphList[i];
    const { dependencies } = item;
    if (dependencies) {
      for (let i in dependencies) {
        graphList.push(moduleAnalysis(dependencies[i]))
      }
    }
  }
  const graph = {};
  graphList.forEach(({ filename, dependencies, code }) =&gt; {
    graph[filename] = {
      dependencies,
      code
    }
  });
  return graph;
}</code></pre>
<p>分析出的所有依赖对象</p>
<pre><code class="json">{
  &#39;./src/index.js&#39;: {
    dependencies: { &#39;./learn.js&#39;: &#39;./src/learn.js&#39; },
    code: &#39;&quot;use strict&quot;;\n&#39; +
      &#39;\n&#39; +
      &#39;var _learn = _interopRequireDefault(require(&quot;./learn.js&quot;));\n&#39; +
      &#39;\n&#39; +
      &#39;function _interopRequireDefault(obj) { return obj &amp;&amp; obj.__esModule ? obj : { &quot;default&quot;: obj }; }\n&#39; +
      &#39;\n&#39; +
      &#39;console.log(_learn[&quot;default&quot;]);&#39;
  },
  &#39;./src/learn.js&#39;: {
    dependencies: { &#39;./course.js&#39;: &#39;./src/course.js&#39; },
    code: &#39;&quot;use strict&quot;;\n&#39; +
      &#39;\n&#39; +
      &#39;Object.defineProperty(exports, &quot;__esModule&quot;, {\n&#39; +
      &#39;  value: true\n&#39; +
      &#39;});\n&#39; +
      &#39;exports[&quot;default&quot;] = void 0;\n&#39; +
      &#39;\n&#39; +
      &#39;var _course = require(&quot;./course.js&quot;);\n&#39; +
      &#39;\n&#39; +
      &#39;var learnNotify = &quot;time to learn &quot;.concat(_course.course);\n&#39; +
      &#39;var _default = learnNotify;\n&#39; +
      &#39;exports[&quot;default&quot;] = _default;&#39;
  },
  &#39;./src/course.js&#39;: {
    dependencies: {},
    code: &#39;&quot;use strict&quot;;\n&#39; +
      &#39;\n&#39; +
      &#39;Object.defineProperty(exports, &quot;__esModule&quot;, {\n&#39; +
      &#39;  value: true\n&#39; +
      &#39;});\n&#39; +
      &#39;exports.course = void 0;\n&#39; +
      &quot;var course = &#39;webpack&#39;;\n&quot; +
      &#39;exports.course = course;&#39;
  }
}</code></pre>
<h4 id="生成代码"><a href="#生成代码" class="headerlink" title="生成代码"></a>生成代码</h4><pre><code class="js">const generateCode = (entry) =&gt; {
    const graph = JSON.stringify(analysisDependenciesGraph(entry));
    return `
        (function(graph){
            function require(module) { 
                function localRequire(relativePath) {
                    return require(graph[module].dependencies[relativePath]);
                }
                var exports = {};
                (function(require, exports, code){
                    eval(code)
                })(localRequire, exports, graph[module].code);
                return exports;
            };
            require(&#39;${entry}&#39;)
        })(${graph});
    `;
}</code></pre>
<p>生成后的代码就可以直接在浏览器运行了</p>
<p><img src="" data-original="https://gitee.com/alannum3/MyImages/raw/master/img/image-20200613160248899.png" alt="image-20200613160248899"></p>
<p>完整代码</p>
<pre><code class="js">const fs = require(&#39;fs&#39;);
const parser = require(&#39;@babel/parser&#39;);
const traverse = require(&#39;@babel/traverse&#39;).default;
const path = require(&#39;path&#39;);
const babel = require(&#39;@babel/core&#39;);
// 命令行高亮工具
const highlight = require(&#39;cli-highlight&#39;).highlight

const moduleAnalysis = (filename) =&gt; {
  // 读取出index.js文件内容
  const content = fs.readFileSync(filename, &#39;utf-8&#39;);
  // 将文件内容转化为抽象语法树
  const ast = parser.parse(content, {
    sourceType: &#39;module&#39;
  });
  const dependencies = {};
  // 遍历抽象语法树
  traverse(ast, {
    ImportDeclaration({ node }) {
      // 文件对应目录./src
      const dirPath = path.dirname(filename);
      // 绝对路径./src/learn.js(window操作系统)
      let filePath = (&#39;./&#39; + path.join(dirPath, node.source.value)).replace(&#39;\\&#39;, &#39;/&#39;);
      dependencies[node.source.value] = filePath;
      // { &#39;./learn.js&#39;: &#39;./src/learn.js&#39; }
      console.log(dependencies);
    }
  });
  // 转化成浏览器可以执行的代码
  const { code } = babel.transformFromAst(ast, null, {
    presets: [&#39;@babel/preset-env&#39;]
  });
  return {
    filename,
    dependencies,
    code
  }
}

const analysisDependenciesGraph = (entry) =&gt; {
  const entryModule = moduleAnalysis(entry);
  const graphList = [entryModule];
  for (let i = 0; i &lt; graphList.length; i++) {
    const item = graphList[i];
    const { dependencies } = item;
    if (dependencies) {
      for (let j in dependencies) {
        graphList.push(moduleAnalysis(dependencies[j]))
      }
    }
  }
  const graph = {};
  graphList.forEach(({ filename, dependencies, code }) =&gt; {
    graph[filename] = {
      dependencies,
      code
    }
  });
  return graph;
}

const generateCode = (entry) =&gt; {
    const graph = JSON.stringify(analysisDependenciesGraph(entry));
    return `
        (function(graph){
            function require(module) { 
                function localRequire(relativePath) {
                    return require(graph[module].dependencies[relativePath]);
                }
                var exports = {};
                (function(require, exports, code){
                    eval(code)
                })(localRequire, exports, graph[module].code);
                return exports;
            };
            require(&#39;${entry}&#39;)
        })(${graph});
    `;
}

const code = generateCode(&#39;./src/index.js&#39;);

console.log(highlight(code));</code></pre>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>到这里总算是对webpack有了大体的了解了。奈何当我学完webpack后看到了<strong>vite</strong>这个东西😒。。。</p>
<p><img src="" data-original="https://gitee.com/alannum3/MyImages/raw/master/img/image-20200615160241265.png" alt="image-20200615160241265"></p>

  
  
    
    <div class='footer'>
      
        <div class='references'>
          <section class='header'>
            
              <i class="fas fa-quote-left fa-fw" aria-hidden="true"></i>
            
            <span>参考资料</span>
          </section>
          <section class='body'>
            <ul>
              
                <li>
                  <a href="https://coding.imooc.com/class/chapter/316.html#Anchor" rel="external nofollow noopener noreferrer" target="_blank">
                  https://coding.imooc.com/class/chapter/316.html#Anchor
                  </a>
                </li>
              
                <li>
                  <a href="https://webpack.js.org/" rel="external nofollow noopener noreferrer" target="_blank">
                  https://webpack.js.org/
                  </a>
                </li>
              
                <li>
                  <a href="https://www.babeljs.cn/docs/" rel="external nofollow noopener noreferrer" target="_blank">
                  https://www.babeljs.cn/docs/
                  </a>
                </li>
              
            </ul>
          </section>
        </div>
      
      
      
        <div class='copyright'>
          <blockquote>
            
              
                <p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</p>

              
            
              
                <p>本文永久链接是：<a href=https://alanwang.site/posts/f9d92613/>https://alanwang.site/posts/f9d92613/</a></p>
              
            
          </blockquote>
        </div>
      
      
    </div>
  
  
    


  <div class='article-meta' id="bottom">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2020-06-13T16:06:00+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2020年6月13日 16:06</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/tags/webpack4-0/" rel="nofollow"><i class="fas fa-tags fa-fw" aria-hidden="true"></i><p>webpack4.0</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer"
          
          href="http://connect.qq.com/widget/shareqq/index.html?url=https://alanwang.site/posts/f9d92613/&title=webpack4.0进阶（三） - Alan|前端博客&summary=手写简单的loader、Plugin、简单的webpack"
          
          >
          
            <img src="" data-original="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer"
          
          href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://alanwang.site/posts/f9d92613/&title=webpack4.0进阶（三） - Alan|前端博客&summary=手写简单的loader、Plugin、简单的webpack"
          
          >
          
            <img src="" data-original="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer"
          
          href="http://service.weibo.com/share/share.php?url=https://alanwang.site/posts/f9d92613/&title=webpack4.0进阶（三） - Alan|前端博客&summary=手写简单的loader、Plugin、简单的webpack"
          
          >
          
            <img src="" data-original="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png">
          
        </a>
      
    
      
    
      
    
  </div>
</div>



        
      
    </div>
  </div>


  
  

  
    <div class="prev-next">
      
        <a class='prev' href='/posts/fc7889ef/'>
          <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>TypeScript学习总结（一）</p>
          <p class='content'>TypeScript常用知识点总结


什么是TypeScriptTypeScript是JavaScript的一个超集，在JavaScript的基础上增加了可选的静态类型和基于类的面向对象编程。...</p>
        </a>
      
      
        <a class='next' href='/posts/b4c78541/'>
          <p class='title'>webpack4.0进阶（二）<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
          <p class='content'>TS、Eslint、webpack性能优化


基础内容打包TS文件使用ts-loader
npm i ts-loader typescript -D项目目录如下：
ts-test
 ├── d...</p>
        </a>
      
    </div>
  
</article>


  

  <article class="post white-box reveal shadow" id="comments">
    <p ct><i class='fas fa-comments'></i> 评论</p>
    
    <div id="valine_container" class="valine_thread">
  <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
</div>

  </article>






</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper shadow desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#手写简单的loader"><span class="toc-text">手写简单的loader</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#手写简单的Plugin"><span class="toc-text">手写简单的Plugin</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#react和vue脚手架webpack配置"><span class="toc-text">react和vue脚手架webpack配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#手写一个简单的webpack打包工具"><span class="toc-text">手写一个简单的webpack打包工具</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#处理入口文件找到所有import文件"><span class="toc-text">处理入口文件找到所有import文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#通过入口文件分析出所有文件依赖"><span class="toc-text">通过入口文件分析出所有文件依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#生成代码"><span class="toc-text">生成代码</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#总结"><span class="toc-text">总结</span></a></li></ol>
    </div>
  </section>


  


</aside>



        
        
          <!--此文件用来存放一些不方便取值的变量-->
<!--思路大概是将值藏到重加载的区域内-->

<script>
  window.pdata={}
  pdata.ispage=true;
  pdata.postTitle="webpack4.0进阶（三）";
  pdata.commentPath="";
  pdata.commentPlaceholder="";

  var l_header=document.getElementById("l_header");
  
  l_header.classList.remove("show");
  
</script>

        
      </div>
      
  
  <footer class="footer clearfix">
    <br><br>
    
      
        <div class="aplayer-container">
          


        </div>
      
    
      
        <br>
        <div class="social-wrapper">
          
            
              <a href="mailto:alannum3@qq.com"
                class="social fas fa-envelope flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
                
              </a>
            
          
            
              <a href="https://github.com/3Alan"
                class="social fab fa-github flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
                
              </a>
            
          
            
              <a href="tencent://message/?uin=1540703192"
                class="social fab fa-qq flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
                
              </a>
            
          
            
          
            
          
        </div>
      
    
      
        <div><p>博客内容遵循 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p>
</div>
      
    
      
        <div class='copyright'>
        <p><a href="https://alanwang.site/">Copyright © 2020 Alan</a></p>

        </div>
      
    
  </footer>


      <a id="s-top" class="fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
    </div>
  </div>
  <div>
    <script>
window.volantis={};
window.volantis.loadcss=document.getElementById("loadcss");
/********************脚本懒加载函数********************************/
function loadScript(src, cb) {
var HEAD = document.getElementsByTagName('head')[0] || document.documentElement;
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
if (cb) script.onload = cb;
script.setAttribute('src', src);
HEAD.appendChild(script);
}
//https://github.com/filamentgroup/loadCSS
var loadCSS = function( href, before, media, attributes ){
	var doc = window.document;
	var ss = doc.createElement( "link" );
	var ref;
	if( before ){
		ref = before;
	}
	else {
		var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
		ref = refs[ refs.length - 1];
	}
	var sheets = doc.styleSheets;
	if( attributes ){
		for( var attributeName in attributes ){
			if( attributes.hasOwnProperty( attributeName ) ){
				ss.setAttribute( attributeName, attributes[attributeName] );
			}
		}
	}
	ss.rel = "stylesheet";
	ss.href = href;
	ss.media = "only x";
	function ready( cb ){
		if( doc.body ){
			return cb();
		}
		setTimeout(function(){
			ready( cb );
		});
	}
	ready( function(){
		ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
	});
	var onloadcssdefined = function( cb ){
		var resolvedHref = ss.href;
		var i = sheets.length;
		while( i-- ){
			if( sheets[ i ].href === resolvedHref ){
				return cb();
			}
		}
		setTimeout(function() {
			onloadcssdefined( cb );
		});
	};
	function loadCB(){
		if( ss.addEventListener ){
			ss.removeEventListener( "load", loadCB );
		}
		ss.media = media || "all";
	}
	if( ss.addEventListener ){
		ss.addEventListener( "load", loadCB);
	}
	ss.onloadcssdefined = onloadcssdefined;
	onloadcssdefined( loadCB );
	return ss;
};
</script>
<script>
  
  loadCSS("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14/css/all.min.css", window.volantis.loadcss);
  
  
  
  
  loadCSS("https://cdn.jsdelivr.net/npm/highlight.js@10.0.3/styles/atom-one-dark.min.css", window.volantis.loadcss);
  
</script>
<!-- required -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.min.js"></script>

<script>
  function pjax_fancybox() {
    $(".md .gallery").find("img").each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("class", "fancybox");
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 判断当前页面是否存在描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".md .gallery").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  function SCload_fancybox() {
    if ($(".md .gallery").find("img").length == 0) return;
    loadCSS("https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css", document.getElementById("loadcss"));
    setTimeout(function() {
      loadScript('https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js', pjax_fancybox)
    }, 1);
  };
  $(function () {
    SCload_fancybox();
  });
</script>


<!-- internal -->

  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
        var imgs=["https://gitee.com/alannum3/MyImages/raw/master/img/triangles-3321900_1920.png", "https://gitee.com/alannum3/MyImages/raw/master/img/img-8e2c27a1a7510d3b73317e96ec2f4b72.jpg", "https://gitee.com/alannum3/MyImages/raw/master/img/img-2da8b0f6ac052b7b9402dea246a56701.jpg", "https://gitee.com/alannum3/MyImages/raw/master/img/img-389c21fac02e9980506b6f7ff7f130f6.jpg", "https://gitee.com/alannum3/MyImages/raw/master/img/img-b7f5935e94f6deda4fda5e2820c48bef.jpg", "https://gitee.com/alannum3/MyImages/raw/master/img/img-3c991ba94430b0ddf426d9062bbea403.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/002.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/003.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/004.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/005.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/006.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/012.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/016.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/019.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/025.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/033.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/034.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/035.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/038.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/039.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/042.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/046.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/051.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/052.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/054.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/056.jpg"];
        if ('true' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
	  function Pjax_backstretch(){
        
          $.backstretch(
            imgs,
          {
            duration: "20000",
            fade: "1500"
          });
        
	  }
	  loadScript("https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js",Pjax_backstretch)
    </script>
  



  
  

  <div id="rightmenu-wrapper">
    <ul class="list-v rightmenu" id="rightmenu-content">
      <li class='option'>
        <a class='vlts-menu opt fix-cursor-default' id='menu-copy-text' onclick="document.execCommand('copy')"><i class='fa fa-copy fa-fw'></i>复制文本</a>
        <hr id='hr-text'>
        <a class='vlts-menu opt fix-cursor-default' id='menu-copy-href'><i class='fa fa-link fa-fw'></i>复制链接</a>
        <a class='vlts-menu opt fix-cursor-default' id='menu-open-href'><i class='fa fa-external-link-square-alt fa-fw'></i>在新标签页打开</a>
        <hr id='hr-href'>
        <a class='vlts-menu opt fix-cursor-default' id='menu-copy-src'><i class='fa fa-image fa-fw'></i>复制图片地址</a>
        <hr id='hr-src'>
      </li>
      
        <li class='navigation'>
          <a class='nav icon-only fix-cursor-default' onclick='history.back()'><i class='fa fa-arrow-left fa-fw'></i></a>
          <a class='nav icon-only fix-cursor-default' onclick='history.forward()'><i class='fa fa-arrow-right fa-fw'></i></a>
          <a class='nav icon-only fix-cursor-default' onclick='window.location.reload()'><i class='fa fa-redo fa-fw'></i></a>
          <a class='nav icon-only fix-cursor-default' href='/'><i class='fa fa-home fa-fw'></i></a>
        </li>
      
      <hr>
      
        
      
        
      
    </ul>
  </div>

  <script>
    window.document.oncontextmenu = function (event) {
      if (event.ctrlKey) return true;
      if (/Android|webOS|BlackBerry/i.test(navigator.userAgent)) return true;
      return popMenu(event);
    };
    document.addEventListener("click", function (event) {
      var mymenu = document.getElementById('rightmenu-wrapper');
      mymenu.style.display = "none";
    });
    function popMenu(event) {
      var mymenu = document.getElementById('rightmenu-wrapper');
      var menuContent = document.getElementById('rightmenu-content');
      var screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
      var screenHeight = document.documentElement.clientHeight || document.body.clientHeight;
      mymenu.style.left = event.clientX + "px"; // 获取鼠标位置
      mymenu.style.top = event.clientY + "px";
      mymenu.style.display = 'block';
      if (event.clientX * 2 > screenWidth) {
        menuContent.classList.add('left');
      } else {
        menuContent.classList.remove('left');
      }
      if (event.clientY * 2 > screenHeight) {
        menuContent.classList.add('top');
      } else {
        menuContent.classList.remove('top');
      }

      let hrText = document.getElementById('hr-text');
      let hrSrc = document.getElementById('hr-src');
      let hrHref = document.getElementById('hr-href');

      // 选中图片
      let copySrc = document.getElementById('menu-copy-src');
      if (copySrc != undefined) {
        if (event.target.currentSrc) {
          copySrc.style.display = 'block';
          copySrc.addEventListener("click", function (e) {
            copyString(event.target.currentSrc);
          },{once: true});
          hrSrc.style.display = 'block';
        } else {
          copySrc.style.display = 'none';
          hrSrc.style.display = 'none';
        }
      }

      // 选中按钮
      // 判断是不是按钮
      let href = '';
      if (event.path) {
        for (i = 0; i < event.path.length; i++) {
          if (event.path[i].href != undefined && event.path[i].href.length > 0) {
            href = event.path[i].href;
          }
        }
      }

      let copyText = document.getElementById('menu-copy-text');
      copyText.style.display = 'none';
      hrText.style.display = 'none';
      if (href.length == 0) {
        // 选中文本
        if (window.getSelection().toString()) {
          if ('true' == 'true') {
            copyText.style.display = 'block';
            hrText.style.display = 'block';
          }
        }
      }

      // 在新标签页打开
      let openHref = document.getElementById('menu-open-href');
      if (openHref != undefined) {
        if (href.length > 0) {
          openHref.style.display = 'block';
          openHref.addEventListener("click", function (e) {
            window.open(href);
          },{once: true});
          hrHref.style.display = 'block';
        } else {
          openHref.style.display = 'none';
          hrHref.style.display = 'none';
        }
      }
      // 复制链接
      let copyHref = document.getElementById('menu-copy-href');
      if (copyHref != undefined) {
        if (href.length > 0) {
          copyHref.style.display = 'block';
          copyHref.addEventListener("click", function (e) {
            copyString(href);
          },{once: true});
        } else {
          copyHref.style.display = 'none';
        }
      }

      // 有音乐播放器
      if ('false' == true && ('home,music'||[]).includes('music')) {
        // 如果有aplayer，初始化一下
      	try {
      		checkAPlayer();
          updateTitle();
      	} catch (error) {
      		console.log(error);
      	}
      }

      return false; // 该行代码确保系统自带的右键菜单不会被调出
    }
    function hideMenu() {
      document.getElementById('rightmenu-wrapper').style.display = 'none';
    }
    function copyString(str) {
      const input = document.createElement('input');
      input.setAttribute('readonly', 'readonly');
      document.body.appendChild(input);
      input.setAttribute('value', str);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
    }
    document.execCommand('click');
  </script>







  <script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazyload",
    threshold: 0
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    lazyLoadInstance.update();
  });
  document.addEventListener('pjax:complete', function () {
    lazyLoadInstance.update();
  });
</script>




  
  
    <script>
      window.FPConfig = {
        delay: 0,
        ignoreKeywords: [],
        maxRPS: 5,
        hoverDelay: 25
      };
    </script>
    <script defer src="https://cdn.jsdelivr.net/gh/gijo-varghese/flying-pages@2.1.2/flying-pages.min.js"></script>
  




  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
    var clipboard = new ClipboardJS('.btn-copy', {
        target: function (trigger) {
            return trigger.nextElementSibling
        }
    });
    function wait(callback, seconds) {
        var timelag = null;
        timelag = window.setTimeout(callback, seconds)
    }
    function pjax_initCopyCode() {
		if($(".highlight .code pre").length+$(".article pre code").length==0)return;
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        $(".article pre code").before(copyHtml);
        clipboard.off('success').on('success', function (e) {
            let $btn = $(e.trigger);
            $btn.addClass('copied');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-check-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPIED';
            wait(function () {
                $icon.removeClass('fa-check-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        });
        clipboard.off('error').on('error', function (e) {
            e.clearSelection();
            let $btn = $(e.trigger);
            $btn.addClass('copy-failed');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-times-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPY FAILED';
            wait(function () {
                $icon.removeClass('fa-times-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        })
    }
    $(function () {
        pjax_initCopyCode()
    });
</script>








  
  
<script src="https://cdn.jsdelivr.net/npm/valine@1.4/dist/Valine.min.js"></script>


<script>
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link'.split(',').filter(function (item) {
    return GUEST_INFO.indexOf(item) > -1
  });
  var REQUIRED_FIELDS = ['nick', 'mail', 'link'];
  var requiredFields = 'nick,mail'.split(',').filter(function (item) {
    return REQUIRED_FIELDS.indexOf(item) > -1
  });

  function emoji(path, idx, ext) {
    return path + "/" + path + "-" + idx + "." + ext;
  }

  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }

  function pjax_valine() {
    if(!document.querySelectorAll("#valine_container")[0])return;

    let pagePlaceholder = pdata.commentPlaceholder || "快来评论吧~";

    let path = pdata.commentPath;
    if (path.length == 0) {
      let defaultPath = '';
      path = defaultPath || decodeURI(window.location.pathname);
    }

    var valine = new Valine();
    valine.init({
      el: '#valine_container',
      meta: meta,
      placeholder: pagePlaceholder,
      path: path,
      appId: "aowgxqHE7wB4I8HLWqC4c4Ut-MdYXbMMI",
      appKey: "37wkY4T3cM7nV2UWV7EIEHPy",
      pageSize: '10',
      avatar: 'robohash',
      lang: 'zh-cn',
      visitor: 'true',
      highlight: 'true',
      mathJax: 'false',
      enableQQ: 'true',
      recordIP: 'false',
      requiredFields: requiredFields,
      emojiCDN: 'https://cdn.jsdelivr.net/gh/volantis-x/cdn-emoji/valine/',
      emojiMaps: emojiMaps
    })
  }

  $(function () {
    pjax_valine();
  });
</script>




  <script defer src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js" data-pjax></script>


  
<script src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@4.1.5/source/js/app.min.js"></script>




  
  
<script src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@4.1.5/source/js/search.min.js"></script>

  


<!-- optional -->

  <script>
const SearchServiceimagePath="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@master/img/";
const ROOT =  ("/" || "/").endsWith('/') ? ("/" || "/") : ("//" || "/" );
function listenSearch(){
  
    customSearch = new HexoSearch({
      imagePath: SearchServiceimagePath
    });
  
}
document.addEventListener("DOMContentLoaded", listenSearch);

</script>







  
<script src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@2/js/comment_typing.js"></script>




  
    
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.18.1/build/highlight.min.js"></script>

    <script>hljs.initHighlightingOnLoad();</script>
  



  <script defer>

  const LCCounter = {
    app_id: 'aowgxqHE7wB4I8HLWqC4c4Ut-MdYXbMMI',
    app_key: '37wkY4T3cM7nV2UWV7EIEHPy',
    custom_api_server: '',

    // 查询存储的记录
    getRecord(Counter, url, title) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({url})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {url, title: title, times: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    },

    // 发起自增请求
    increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    },

    // 构建自增请求体
    buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "times": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    },

    // 校验是否为有效的 UV
    validUV() {
      var key = 'LeanCloudUVTimestamp';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    },

    addCount(Counter) {
      var enableIncr = '' === 'true' && window.location.hostname !== 'localhost';
      enableIncr = true;
      var getterArr = [];
      var incrArr = [];
      // 请求 PV 并自增
      var pvCtn = document.querySelector('#lc-sv');
      if (pvCtn || enableIncr) {
        var pvGetter = this.getRecord(Counter, 'https://alanwang.site' + '/#lc-sv', 'Visits').then((record) => {
          incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-sv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + 1;
              if (pvCtn) {
                pvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#lc-uv');
      if (uvCtn || enableIncr) {
        var uvGetter = this.getRecord(Counter, 'https://alanwang.site' + '/#lc-uv', 'Visitors').then((record) => {
          var vuv = this.validUV();
          vuv && incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-uv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + (vuv ? 1 : 0);
              if (uvCtn) {
                uvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(uvGetter);
      }

      // 请求文章的浏览数，如果是当前页面就自增
      var allPV = document.querySelectorAll('#lc-pv');
      if (allPV.length > 0 || enableIncr) {
        for (i = 0; i < allPV.length; i++) {
          let pv = allPV[i];
          let title = pv.getAttribute('data-title');
          var url = 'https://alanwang.site' + pv.getAttribute('data-path');
          if (url) {
            var viewGetter = this.getRecord(Counter, url, title).then((record) => {
              // 是当前页面就自增
              let curPath = window.location.pathname;
              if (curPath.includes('index.html')) {
                curPath = curPath.substring(0, curPath.lastIndexOf('index.html'));
              }
              if (pv.getAttribute('data-path') == curPath) {
                incrArr.push(this.buildIncrement(record.objectId));
              }
              if (pv) {
                var ele = pv.querySelector('#lc-pv #number');
                if (ele) {
                  if (pv.getAttribute('data-path') == curPath) {
                    ele.innerText = (record.times || 0) + 1;
                  } else {
                    ele.innerText = record.times || 0;
                  }
                  pv.style.display = 'inline';
                }
              }
            });
            getterArr.push(viewGetter);
          }
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && this.increment(Counter, incrArr);
        })
      }

    },


    fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': this.app_id,
            'X-LC-Key': this.app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      this.addCount(Counter);
    },

    refreshCounter() {
      var api_server = this.app_id.slice(-9) !== '-MdYXbMMI' ? this.custom_api_server : `https://${ this.app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;
      if (api_server) {
        this.fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + this.app_id)
          .then(resp => resp.json())
          .then(({api_server}) => {
            this.fetchData('https://' + api_server);
          });
      }
    }

  };

  LCCounter.refreshCounter();

  document.addEventListener('pjax:complete', function () {
    LCCounter.refreshCounter();
  });
</script>




  <script>
const rootElement = document.documentElement;
const darkModeStorageKey = "user-color-scheme";
const rootElementDarkModeAttributeName = "data-user-color-scheme";

const setLS = (k, v) => {
  try {
    localStorage.setItem(k, v);
  } catch (e) {
    console.log(e.message);
  }
};

const removeLS = (k) => {
  try {
    localStorage.removeItem(k);
  } catch (e) {
    console.log(e.message);
  }
};

const getLS = (k) => {
  try {
    return localStorage.getItem(k);
  } catch (e) {
    console.log(e.message);
    return null;
  }
};

const getModeFromCSSMediaQuery = () => {
  return window.matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
};

const resetRootDarkModeAttributeAndLS = () => {
  rootElement.removeAttribute(rootElementDarkModeAttributeName);
  removeLS(darkModeStorageKey);
};

const validColorModeKeys = {
  dark: true,
  light: true,
};

const applyCustomDarkModeSettings = (mode) => {
  const currentSetting = mode || getLS(darkModeStorageKey);

  if (currentSetting === getModeFromCSSMediaQuery()) {
    resetRootDarkModeAttributeAndLS();
  } else if (validColorModeKeys[currentSetting]) {
    rootElement.setAttribute(rootElementDarkModeAttributeName, currentSetting);
  } else {
    resetRootDarkModeAttributeAndLS();
  }
};

const invertDarkModeObj = {
  dark: "light",
  light: "dark",
};

/**
 * get target mode
 */
const toggleCustomDarkMode = () => {
  let currentSetting = getLS(darkModeStorageKey);

  if (validColorModeKeys[currentSetting]) {
    currentSetting = invertDarkModeObj[currentSetting];
  } else if (currentSetting === null) {
    currentSetting = invertDarkModeObj[getModeFromCSSMediaQuery()];
  } else {
    return;
  }
  setLS(darkModeStorageKey, currentSetting);
  return currentSetting;
};

/**
 * bind click event for toggle button
 */
function bindToggleButton() {
	var btn=$("#wrapper .toggle-mode-btn");
    btn.on('click',(e) => {
      const mode = toggleCustomDarkMode();
      applyCustomDarkModeSettings(mode);
    });
}

applyCustomDarkModeSettings();
document.addEventListener("DOMContentLoaded", bindToggleButton);
document.addEventListener("pjax:success", bindToggleButton);

</script>





<!-- baidu Analytics -->
<script>
var _hmt = _hmt || [];
(function() {
  setTimeout(function() {
	var hm = document.createElement("script");
	hm.src = "https://hm.baidu.com/hm.js?ff1856f91533fcea9c8c2fe5a1b06fe7";
	hm.defer=true;
	var s = document.getElementsByTagName("script")[0];
	s.parentNode.insertBefore(hm, s);
  }, 5000);
})();
</script>


<script>
function listennSidebarTOC() {
  const navItems = document.querySelectorAll(".toc li");
  if (!navItems.length) return;
  const sections = [...navItems].map((element) => {
    const link = element.querySelector(".toc-link");
    const target = document.getElementById(
      decodeURI(link.getAttribute("href")).replace("#", "")
    );
    link.addEventListener("click", (event) => {
      event.preventDefault();
      window.scrollTo({
		top: target.offsetTop + 100,
		
		behavior: "smooth"
		
	  });
    });
    return target;
  });

  function activateNavByIndex(target) {
    if (target.classList.contains("active-current")) return;

    document.querySelectorAll(".toc .active").forEach((element) => {
      element.classList.remove("active", "active-current");
    });
    target.classList.add("active", "active-current");
    let parent = target.parentNode;
    while (!parent.matches(".toc")) {
      if (parent.matches("li")) parent.classList.add("active");
      parent = parent.parentNode;
    }
  }

  function findIndex(entries) {
    let index = 0;
    let entry = entries[index];
    if (entry.boundingClientRect.top > 0) {
      index = sections.indexOf(entry.target);
      return index === 0 ? 0 : index - 1;
    }
    for (; index < entries.length; index++) {
      if (entries[index].boundingClientRect.top <= 0) {
        entry = entries[index];
      } else {
        return sections.indexOf(entry.target);
      }
    }
    return sections.indexOf(entry.target);
  }

  function createIntersectionObserver(marginTop) {
    marginTop = Math.floor(marginTop + 10000);
    let intersectionObserver = new IntersectionObserver(
      (entries, observe) => {
        let scrollHeight = document.documentElement.scrollHeight + 100;
        if (scrollHeight > marginTop) {
          observe.disconnect();
          createIntersectionObserver(scrollHeight);
          return;
        }
        let index = findIndex(entries);
        activateNavByIndex(navItems[index]);
      },
      {
        rootMargin: marginTop + "px 0px -100% 0px",
        threshold: 0,
      }
    );
    sections.forEach((element) => {
      element && intersectionObserver.observe(element);
    });
  }
  createIntersectionObserver(document.documentElement.scrollHeight);
}

document.addEventListener("DOMContentLoaded", listennSidebarTOC);
document.addEventListener("pjax:success", listennSidebarTOC);
</script>

<!-- more -->




    
      


<script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.min.js"></script>


<script>
    var pjax;
    document.addEventListener('DOMContentLoaded', function () {
      pjax = new Pjax({
        elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([pjax-fancybox])',
        selectors: [
          "title",
          "#l_cover",
          "#pjax-container",
          "#pjax-header-nav-list"
        ],
        cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
        timeout: 5000
      });
    });

    document.addEventListener('pjax:send', function (e) {
      //window.stop(); // 相当于点击了浏览器的停止按钮

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      window.subData = null; // 移除标题（用于一二级导航栏切换处）
      if (typeof $.fancybox != "undefined") {
        $.fancybox.close();    // 关闭弹窗
      }
      volantis.$switcher.removeClass('active'); // 关闭移动端激活的搜索框
      volantis.$header.removeClass('z_search-open'); // 关闭移动端激活的搜索框
      volantis.$wrapper.removeClass('sub'); // 跳转页面时关闭二级导航

      // 解绑事件 避免重复监听
      volantis.$topBtn.unbind('click');
      $('.menu a').unbind('click');
      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');
	  
    });

    document.addEventListener('pjax:complete', function () {
      // 关于百度统计对 SPA 页面的处理：
      // 方案一：百度统计>管理>单页应用设置中，打开开启按钮即可对SPA进行统计。 https://tongji.baidu.com/web/help/article?id=324
      // 方案二：取消注释下列代码。 https://tongji.baidu.com/web/help/article?id=235
      // 
      // _hmt.push(['_trackPageview', document.location.pathname]);
      // 

      // 关于谷歌统计对 SPA 页面的处理：
      // 当应用以动态方式加载内容并更新地址栏中的网址时，也应该更新通过 gtag.js 存储的网页网址。
      // https://developers.google.cn/analytics/devguides/collection/gtagjs/single-page-applications?hl=zh-cn
      

      $('.nav-main').find('.list-v').not('.menu-phone').removeAttr("style",""); // 移除小尾巴的移除
      $('.menu-phone.list-v').removeAttr("style",""); // 移除小尾巴的移除
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
      try{
          if (typeof $.fancybox == "undefined") {
            SCload_fancybox();
          } else {
            pjax_fancybox();
          }
        
		  Pjax_backstretch()
        
        
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightBlock(block);
        });
        
        
        
        
          pjax_initCopyCode();
        
        
          pjax_valine();
        
        
        
        
      } catch (e) {
        console.log(e);
      }
	  
    });

    document.addEventListener('pjax:error', function (e) {
	  
      window.location.href = e.triggerElement.href;
    });
</script>

    
  </div>
<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=i;var e=n.imageLazyLoadSetting.isSPA,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function i(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight||document.documentElement.clientHeight)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},n.src=i}()}i(),n.addEventListener("scroll",function(){var t,e;t=i,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>
</html>
